﻿using System.Collections.Generic;

namespace ParboiledSharp
{
    class ValueStackList
    {
        private readonly List<ValueStack> _stacks;

        internal ValueStackList()
        {
            _stacks = new List<ValueStack>(50);
            PushToList(new ValueStack());
        }

        public void Clear() {
            _stacks.Clear();
        }

        private ValueStack GetTopStack()
        {
            return _stacks[ListCount() - 1];
        }

        private void PopFromList()
        {
          _stacks.RemoveAt(ListCount() - 1);
        }

      private int ListCount()
        {
            return _stacks.Count;
        }

        private void PushToList(ValueStack value)
        {
            _stacks.Add(value);
        }

        public bool IsNewStack()
        {
            return GetTopStack() == null;
        }

        public void CloneValueStack()
        {
            PushToList(null);
        }

        public ValueStack GetLastFilledValueStack()
        {
            for (int i = ListCount() - 1; i >= 0; i--)
            {
                if (_stacks[i] != null)
                {
                    return _stacks[i];
                }
            }
            return null;
        }

        public ValueStack PeekValueStack()
        {
            if (IsNewStack())
            {
                PopFromList();
                ValueStack stack = GetLastFilledValueStack();
                PushToList(stack.Clone());
            }

            return GetTopStack();
        }

        public void PopButSaveLastValueStack()
        {
            if (IsNewStack())
            {
                PopFromList();
                return;
            }
            if (ListCount() >= 2)
            {
                _stacks.RemoveAt(ListCount() - 2);
            }
            else
            {
                _stacks.RemoveAt(0);
            }
        }

        public void DiscardValueStack()
        {
            PopFromList();
        }
    }
}
